package com.auto.autoapp.network

import android.util.Log
import com.auto.autoapp.base.IView
import com.auto.autoapp.data.model.ApiResponse
import com.auto.autoapp.network.interceptor.HeaderInterceptor
import com.auto.autoapp.network.interceptor.LoggingInterceptor
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.ResponseBody
import retrofit2.Converter
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.lang.reflect.Type
import java.util.concurrent.TimeUnit

/**
 * Retrofit 客户端单例
 * 负责创建和配置 Retrofit 实例
 */
object RetrofitClient {

    // 基础 URL，实际使用时应该配置到 BuildConfig 或配置文件中
    private const val BASE_URL = "https://api.langfa.net/"

    // 连接超时时间（秒）
    private const val CONNECT_TIMEOUT = 15L

    // 读取超时时间（秒）
    private const val READ_TIMEOUT = 15L

    // 写入超时时间（秒）
    private const val WRITE_TIMEOUT = 15L

    /**
     * OkHttpClient 实例（懒加载）
     */
    private val okHttpClient: OkHttpClient by lazy {
        OkHttpClient.Builder()
            // 设置连接超时
            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
            // 设置读取超时
            .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
            // 设置写入超时
            .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
            // 添加请求头拦截器
            .addInterceptor(HeaderInterceptor())
            // 添加日志拦截器（应该放在最后，以便记录完整的请求信息）
            .addInterceptor(LoggingInterceptor.create(isDebug = true))
            // 失败后重试
            .retryOnConnectionFailure(true)
            .build()
    }

    /**
     * Retrofit 实例（懒加载）
     */
    private val retrofit: Retrofit by lazy {
        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(okHttpClient)
            // 添加 String 转换器（优先处理纯文本响应）
            .addConverterFactory(ScalarsConverterFactory.create())
            // 添加 Gson 转换器（处理 JSON 响应）
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    /**
     * 创建 API 服务接口
     * @param T API 服务接口类型
     * @return API 服务接口实例
     */
    fun <T> createService(serviceClass: Class<T>): T {
        return retrofit.create(serviceClass)
    }

    /**
     * 创建带自定义 baseUrl 的 API 服务接口
     * @param T API 服务接口类型
     * @param baseUrl 自定义的 baseUrl
     * @return API 服务接口实例
     */
    fun <T> createService(serviceClass: Class<T>, baseUrl: String): T {
        val newRetrofit = Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(okHttpClient)
            // 添加 String 转换器（优先处理纯文本响应）
            .addConverterFactory(ScalarsConverterFactory.create())
            // 添加 Gson 转换器（处理 JSON 响应）
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        return newRetrofit.create(serviceClass)
    }


    fun getApi(): Api {
        return createService(Api::class.java)
    }

    suspend fun <T> request(
        apiCall: suspend () -> ApiResponse<T>,
        iView: IView? = null,
        showLoading: Boolean? = true,
        showFailMsg: Boolean? = true,
        showSuccessMsg: Boolean? = false,
        onStart: (() -> Unit)? = null,
        onFinish: (() -> Unit)? = null,
        onFail: ((Int, String) -> Unit)? = null,
        onSuccess: (T?, String) -> Unit,
    ) {
        try {
            if (showLoading == true) {
                iView?.showLoading()
            }
            onStart?.invoke()
            val result = apiCall()
            if (result.isSuccess()) {
                val successMsg = result.message ?: "success"
                if (showSuccessMsg == true) {
                    iView?.showToast(successMsg)
                }
                onSuccess(result.data, successMsg)
            } else {
                val failMsg = result.message ?: "fail"
                if (showFailMsg == true) {
                    iView?.showToast(failMsg)
                }
                onFail?.invoke(result.tag ?: -1, failMsg)
            }
            onFinish?.invoke()
            if (showLoading == true) {
                iView?.hideLoading()
            }
        } catch (e: Exception) {
            if (showLoading == true) {
                iView?.hideLoading()
            }
            if (showFailMsg == true) {
                iView?.showToast(e.message ?: "err")
            }
            onFail?.invoke(-1, e.message ?: "err")
            onFinish?.invoke()
        }


    }

//    fun <R, T> executeRequestWithTransform(
//        apiCall: suspend () -> R,
//        transform: (R) -> T
//    ): Flow<NetworkResult<T>> = flow {
//        emit(NetworkResult.Loading)
//        try {
//            val response = apiCall()
//            val data = transform(response)
//            emit(NetworkResult.Success(data))
//        } catch (e: Exception) {
//            val error = handleException(e)
//            emit(NetworkResult.Error(error.message ?: "未知错误", error.code))
//            Log.e(TAG, "API request failed", e)
//        }
//    }.flowOn(Dispatchers.IO)
}

/**
 * 扩展函数：简化 API 服务创建
 */
inline fun <reified T> RetrofitClient.create(): T {
    return createService(T::class.java)
}


